﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Polaris.Common;
using Polaris.Domain.Model.Entity.Exception;
using Polaris.Domain.Model.Enum;
using Polaris.EntityFrameworkCore;
using System.Net;
using System.Reflection;
using Polaris.Domain.Model.Dto;
using System.Net.NetworkInformation;
using ZXing;
using ZXing.Common;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Png;
using Polaris.Domain.Interfaces.Admin;
using Polaris.Domain.Model.Dto.Home.Request;

namespace Polaris.WebApi.Controllers.Admin
{
    /// <summary>
    /// 首页接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class HomeController : BaseController
    {

        private readonly IWebHostEnvironment _env;
        private readonly PolarisDbContext _polarisDbContext;
        private readonly IHome _home;
        private readonly string _emailHtmlTemp = @"<!DOCTYPE html>
<html lang=""zh-CN"">

<head>
    <meta charset=""UTF-8"">
    <title>评论回复通知</title>
    <style>
        body {
            font-family: ""Microsoft YaHei"", ""Segoe UI"", sans-serif;
            line-height: 1.6;
            max-width: 600px;
            margin: 0rem auto;
            padding: 0 20px;
            color: #333;
            height: 100vh;
            display: flex;
            justify-content: center;
            flex-direction: column;
        }

        .header-img {
            text-align: center;
        }

        .header-img img {
            border-radius: 50%;
            width: 2rem;
        }

        .header {
            color: #2c3e50;
            margin-bottom: 25px;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
            text-align: center;
            font-size: .7rem;
        }

        .header span {
            font-weight: bold;
        }

        .reply-info {
            color: #666;
            margin: 15px 0;
            font-size: .8rem;
        }

        .reply-info strong {
            color: #3498db;
        }

        .reply-info-content {
            border: 1px solid #f3c2e1;
            border-radius: .3rem;
            padding: 1rem;
            background: #f3c2e1;
            line-height: 1rem;
            font-size: .7rem;
        }

        .quote {
            background-color: #f8f9fa;
            border-left: 4px solid #e0e0e0;
            padding: 12px 20px;
            margin: 15px 0;
            color: #666;
        }

        .literary-quote {
            font-style: italic;
            color: #7f8c8d;
            margin: 20px 0;
            padding-left: 15px;
            border-left: 2px solid #bdc3c7;
            font-size: .5rem;
        }

        .footer {
            font-size: 12px;
            color: #95a5a6;
            text-align: center;
            margin-top: 30px;
        }

        hr {
            border: 0;
            height: 1px;
            background: #ecf0f1;
            margin: 25px 0;
        }

        .button {
            text-align: center;
            padding: 1rem;
        }

        button {
            height: 2rem;
            border: none;
            width: 7rem;
            background-color: #488aec;
            color: #ffffff;
            font-size: 0.75rem;
            line-height: 1rem;
            font-weight: 700;
            text-align: center;
            cursor: pointer;
            text-transform: uppercase;
            vertical-align: middle;
            align-items: center;
            border-radius: 0.5rem;
            user-select: none;
            gap: 0.75rem;
            box-shadow:
                0 4px 6px -1px #488aec31,
                0 2px 4px -1px #488aec17;
            transition: all 0.6s ease;
        }

        button:hover {
            box-shadow:
                0 10px 15px -3px #488aec4f,
                0 4px 6px -2px #488aec17;
        }

        button:focus,
        button:active {
            opacity: 0.85;
            box-shadow: none;
        }
    </style>
</head>

<body>
    <div class=""header-img"">
        <img src=""https://img0.baidu.com/it/u=3196617431,1263013381&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500"" alt=""""
            srcset="""">
    </div>
    <div class=""header"">
        您在『<span>2024·前路未尽，初心犹在</span>』的评论有了新的回复呐~
    </div>

    <div class=""reply-info"">
        <strong>Innei</strong> 给您的回复：<br><br>
        <div class=""reply-info-content"">
            加油加油 ♥
        </div>

    </div>

    <div class=""reply-info"">
        你之前的回复是：<br><br>
        <div class=""reply-info-content"">
            关注大佬一年了，感觉大佬是真的热爱这行，无论是文章输出，
            还是更新频率，我都非常佩服。很厉害的一个人，努力的人运气
            不会太差，加油加油(ｓ：ˉ)ｓ
        </div>
    </div>

    <div class=""button"">
        <button>
            查看完整内容
        </button>
    </div>
    <hr>

    <div class=""literary-quote"">
        萤火虫消失之后，那光的轨迹仍久久地印在我的脑际。那微弱浅淡
        的光点，仿佛迷失方向的魂灵，在漆黑厚重的夜幕中彷徨。
        ——《挪威的森林》村上春树
    </div>

    <div class=""footer"">
        本邮件为系统自动发送，请勿直接回复~<br>
        ©2024 Copyright Innei
    </div>
</body>

</html>";

        public HomeController(IWebHostEnvironment env, PolarisDbContext polarisDbContext)
        {
            _env = env;
            _polarisDbContext = polarisDbContext;
        }

        /// <summary>
        /// 获取IP和所属地
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetIp()
        {
            string externalIp = await IpHandler.GetExternalIPAddressAsync();
            var add = IpHandler.IpGetCity(externalIp);

            return SUCCESS(data: new
            {
                ip = externalIp,
                address = add,
                time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            });
        }

        /// <summary>
        /// 根据城市编码获取天气json
        /// </summary>
        /// <param name="cityCode">城市编码</param>
        /// <returns>天气json</returns>
        [HttpGet]
        public IActionResult GetWeatherByCity(string cityCode)
        {
            try
            {
                string? weathhtml = "";
                weathhtml = CacheHelper.GetCache("_weathhtml")?.ToString();
                if (weathhtml != null)
                {
                    return SUCCESS(data: weathhtml);
                }

                //请求的时候我们需要前台给我们传递一个城市数据的ID就是我们下载的文档里面的编号
                //下方的请求连接加上要请求城市的ID编号，就可以请求到
                string url = "http://t.weather.itboy.net/api/weather/city/" + cityCode;
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                request.Timeout = 10000;
                request.UserAgent = "Code Sample Web Client";
                request.Credentials = CredentialCache.DefaultCredentials;
                //HttpWebRequest 对象 获取GetResponse 转换成HttpWebResponse
                System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse;
                //通过HttpWebResponse response.GetResponseStream()获取输出流
                System.IO.Stream str = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(str, System.Text.Encoding.GetEncoding("utf-8"));
                weathhtml = reader.ReadToEnd();
                str.Close();
                reader.Close();

                CacheHelper.SetCache("_weathhtml", weathhtml, DateTime.Now.AddHours(2));
                return SUCCESS(data: weathhtml);
            }
            catch (Exception ex)
            {
                throw new CustomException(ResultCode.FAIL, "请求异常 ：" + ex.Message);
            }
        }

        /// <summary>
        /// 获取文章信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetArticle()
        {
            var fileName = "text.txt";
            var fileContent = "";
            try
            {
                string rootPath = _env.WebRootPath;
                string wwwrootPath = Path.Combine(rootPath, "wwwroot");
                string filePath = Path.Combine(rootPath, fileName);


                fileContent = System.IO.File.ReadAllText(filePath);
            }
            catch (Exception ex)
            {
                throw new CustomException(ResultCode.FAIL, ex.Message); // 或者抛出异常，具体处理取决于你的应用逻辑
            }

            return await Task.FromResult(SUCCESS(data: fileContent));
        }

        /// <summary>
        /// 获取数据库表的结构
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetArchiveTable()
        {
            List<ArchiveTable> archive = new List<ArchiveTable>();
            foreach (var entityType in _polarisDbContext.Model.GetEntityTypes())
            {
                archive.Add(PrintTableStructure(entityType));
            }
            return SUCCESS(data: archive);
        }

        /// <summary>
        /// 每日一言
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetEverydaySaid(bool isCache = false)
        {
            string data = "";
            if (isCache && CacheHelper.Exists("_everydaySaid"))
            {
                data = CacheHelper.GetCache("_everydaySaid").ToString();
            }
            else
            {
                using (var client = new HttpClient())
                {
                    //client.BaseAddress = new Uri("http://open.iciba.com/dsapi/");
                    client.BaseAddress = new Uri("https://api.xygeng.cn/openapi/one");
                    //client.BaseAddress = new Uri("https://v1.hitokoto.cn/");
                    try
                    {
                        HttpResponseMessage response = await client.GetAsync(client.BaseAddress);
                        if (response.IsSuccessStatusCode)
                        {
                            data = await response.Content.ReadAsStringAsync();
                            CacheHelper.SetCache("_everydaySaid", data, DateTime.Now.AddDays(1).AddSeconds(-1));
                            Console.WriteLine(data);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        throw new CustomException(ResultCode.FAIL, e.Message);
                    }
                }
            }

            if (data != null && data != "")
            {
                return SUCCESS(data: JsonConvert.DeserializeObject(data));
            }
            else
            {
                return FAIL("ERROR");
            }

        }

        /// <summary>
        /// 仅检测链接头，不会获取链接的结果。所以速度很快，超时的时间单位为毫秒
        /// </summary>
        /// <param name="url"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetWebStatusCode(string url, int timeout = 5000)
        {
            HttpWebRequest req = null;
            try
            {
                req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
                req.Method = "HEAD";  //这是关键        
                req.Timeout = timeout;
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                return Ok(Convert.ToInt32(res.StatusCode).ToString());
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
            finally
            {
                if (req != null)
                {
                    req.Abort();
                    req = null;
                }
            }

        }

        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="qrCodeText"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetQRCode(string qrCodeText, int width = 300, int height = 300)
        {
            // 创建二维码编码器，指定输出类型为 byte[]
            var barcodeWriter = new BarcodeWriter<BinaryBitmap>
            {
                Format = BarcodeFormat.QR_CODE,  // 设置为二维码格式
                Options = new ZXing.Common.EncodingOptions
                {
                    Width = width,  // 设置二维码宽度
                    Height = height  // 设置二维码高度
                }
            };

            // 生成二维码图像的 BitMatrix
            BitMatrix qrCodeMatrix = barcodeWriter.Encode(qrCodeText);  // 生成二维码的 BitMatrix

            // 获取二维码图像的宽度和高度
            int newWidth = qrCodeMatrix.Width;
            int newHeight = qrCodeMatrix.Height;

            // 使用 ImageSharp 创建图像
            Image<Rgba32> img = new Image<Rgba32>(width, height);

            // 遍历 BitMatrix 的每个像素，将其转换为 ImageSharp 图像
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    // 获取 BitMatrix 中的像素值，true 为黑色，false 为白色
                    Rgba32 pixelColor = qrCodeMatrix[x, y] ? new Rgba32(0, 0, 0) : new Rgba32(255, 255, 255);
                    img[x, y] = pixelColor;
                }
            }

            string base64String = "";
            // 保存二维码图像到内存流
            using (MemoryStream memoryStream = new MemoryStream())
            {
                img.Save(memoryStream, PngFormat.Instance);  // 保存为 PNG 格式
                byte[] byteArray = memoryStream.ToArray();

                base64String = "data:image/jpeg;base64," + Convert.ToBase64String(byteArray);
            }

            return SUCCESS(base64String);
        }

        /// <summary>
        /// 获取网址分类
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetWebSiteType()
        {
            var result = await _home.GetWebSiteType();
            return SUCCESS(result);
        }

        /// <summary>
        /// 新增收藏网址
        /// </summary>
        /// <param name="create"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreateWebSite(CreateWebSiteRequest create)
        {
            await _home.CreateWebSite(create, null);
            return SUCCESS("OK");
        }

        /// <summary>
        /// 获取悄悄话
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetSpaceSaid()
        {
            var list = new List<object>()
            {
                new
                {
                    name="彭平安",
                    time="2025年2月12号 星期一",
                    text= "==情不知所起，一往而深。==\r\n生者可以死，死者可以生，生而不可与死，死而不可复生者，==皆非==情之至也。",
                    imgUrl="https://q8.itc.cn/q_70/images03/20241030/7e4e379bf5b84b6c9fb4a9fec3102d5d.jpeg"
                },
                new
                {
                    name="彭平安",
                    time="2024年12月01号 星期二",
                    text=  "一个ReactDemo \r\n Polaris [ReactDemo](http://localhost:5173/)",
                    imgUrl="https://q8.itc.cn/q_70/images03/20241030/7e4e379bf5b84b6c9fb4a9fec3102d5d.jpeg"
                },
                new
                {
                    name="彭平安",
                    time="2024年11月12号 星期三",
                    text= "来看看一张图片吧![11](https://wx4.sinaimg.cn/mw690/005UJ76vgy1htcqockgebj30km0km0ud.jpg)",
                    imgUrl="https://q8.itc.cn/q_70/images03/20241030/7e4e379bf5b84b6c9fb4a9fec3102d5d.jpeg"
                },
                new
                {
                    name="彭平安",
                    time="2024年09月12号 星期一",
                    text=  "::: warning\r\nwarning\r\n:::\r\n\r\n::: error\r\nerror\r\n:::",
                    imgUrl="https://q8.itc.cn/q_70/images03/20241030/7e4e379bf5b84b6c9fb4a9fec3102d5d.jpeg"
                },
            };

            return await Task.FromResult(SUCCESS(data: list));
        }

        /// <summary>
        /// 发送邮件测试
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult SendEmail()
        {
            return SUCCESS("");
        }

        /// <summary>
        /// 获取表结构
        /// </summary>
        /// <param name="entityType"></param>
        /// <returns></returns>
        private static ArchiveTable PrintTableStructure(IEntityType entityType)
        {
            var tableName = entityType.GetTableName();
            //Console.WriteLine($"Table Name: {tableName}");
            var table = new ArchiveTable();
            table.column = new List<ColumnList>();
            table.tName = tableName;

            foreach (var property in entityType.GetProperties())
            {
                string columnName = property.GetColumnName();
                string dataType = property.ClrType.Name;
                bool isNullable = property.IsNullable;
                bool isKey = property.IsPrimaryKey();

                // 尝试获取自定义的描述信息
                var descriptionAttribute = property.PropertyInfo?.GetCustomAttribute<CommentAttribute>();
                string comment = descriptionAttribute?.Comment ?? "";

                //Console.WriteLine($"Column Name: {columnName}, Type: {dataType}, Nullable: {isNullable}, Comment: {comment}，IsKey：{isKey}");
                table.column.Add(new ColumnList()
                {
                    columnComment = comment,
                    columnIsKey = isKey,
                    columnIsNull = isNullable,
                    columnName = columnName,
                    columnType = dataType
                });

            }
            return table;
        }


    }
}
